<template>
  <el-dialog :title="'上传' + typeText" :visible.sync="uploadVisible" width="50%" :before-close="handleClose" :close-on-click-modal="false" append-to-body>
    <el-form ref="form" label-position="left" :model="upload" label-width="80px" class="upload-video">
      <el-form-item label="上传到">
        <el-select v-model="upload.category" placeholder="请选择分组" size="small">
          <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择文件">
        <el-upload
          ref="upload"
          class="upload-container"
          action=""
          :accept="accept"
          multiple
          :limit="limit"
          :auto-upload="false"
          :http-request="fileUpload"
          :on-progress="fileOnProgress"
          :on-change="fileOnChange"
          :on-remove="fileOnRemove"
          :on-success="fileOnSuccess"
          :show-file-list="false"
          :on-exceed="onExceed"
        >
          <el-button slot="trigger" size="small" type="primary">选取{{ typeText }}</el-button>
          <div slot="tip" class="el-upload__tip">
            最多可上传{{ limit }}个文件
            <span v-if="limit > 1">，按住Ctrl可以多选</span>
          </div>
        </el-upload>
        <el-table :data="uploadListInfo" style="width: 100%" height="250">
          <el-table-column prop="name" label="文件名" />
          <el-table-column prop="size" label="大小" />
          <el-table-column prop="status" label="上传状态" />
          <el-table-column prop="action" label="操作">
            <template slot-scope="scope">
              <el-link :underline="false" type="primary" @click="removeFile(scope.row.name)">移除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-button type="primary" :disabled="disableSubmit" size="small" @click="submitUpload" v-text="btnText">确认上传</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
export default {
  props: {
    uploadVisible: {
      type: Boolean,
      default: false
    },
    category: {
      type: Array,
      require: true,
      default: _ => {
        return [];
      }
    },
    currentCategory: {
      type: Number,
      default: -1
    },
    materialType: {
      type: String,
      default: 'file'
    },
    limit: {
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      upload: {
        category: this.currentCategory
      },
      uploadType: {
        audio: 'audio/*',
        video: 'video/*',
        // file: '.pdf'
        file: '.pdf,.epub'
        // file: '.epub,.doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.txt,.pdf'
      },
      btnText: '确认上传',
      disableSubmit: false,
      uploadList: [],
      uploadListInfo: [],
      attach_ids: [],
      uploading: 0,
      timer: 0
    };
  },
  computed: {
    accept() {
      return this.uploadType[this.materialType];
    },
    options() {
      console.log(this.category)
      return this.category.length > 0 ? this.category[0].children : [];
    },
    typeText() {
      const text = {
        video: '视频',
        audio: '音频',
        file: '文件'
      };

      return text[this.materialType];
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:uploadVisible', false);
    },
    // 格式化文件大小
    renderSize: function(value) {
      if (!value) {
        return '0 Bytes';
      }
      var unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      var index = 0;
      var srcsize = parseFloat(value);
      index = Math.floor(Math.log(srcsize) / Math.log(1024));
      var size = srcsize / Math.pow(1024, index);
      size = size.toFixed(2); // 保留的小数位数
      return size + unitArr[index];
    },
    /** 手动点击上传方法 */
    submitUpload: function() {
      if (this.uploadList.length == 0) {
        this.$message.warning('请选择要上传的素材');
        return false;
      }
      clearInterval(this.timer);
      this.btnText = '正在上传...';
      this.disableSubmit = true;

      this.uploading = this.uploadList.length;
      this.$refs.upload.submit();
      // 全部上传完成时,提交素材
      this.timer = setInterval(() => {
        // 只有全部上传完成时,再提交
        if (this.attach_ids.length != this.uploading) {
          return false;
        }
        clearInterval(this.timer);
        // 提交绑定素材
        this.$http.post(
          '/admin/material/upload',
          {
            category: this.upload.category,
            material_type: this.materialType,
            attach_ids: this.attach_ids
          },
          response => {
            this.$message.success(response.msg);

            this.$emit('reload', {
              ids: this.attach_ids,
              filelist: this.uploadList
            });

            this.$emit('update:uploadVisible', false);
          },
          error => {
            this.$message.error(error.msg);
          }
        );
      }, 200);
    },
    onExceed: function() {
      this.$message.error('最多一次性上传' + this.limit + '个文件');
    },
    /** 自定义文件上传方法,采用分片上传 */
    fileUpload: function(params) {
      // 分片上传 每2M为一片
      this.$upload.submit(params, true, 2);
    },
    fileOnChange: function(file, fileList) {
      if (file.status === 'ready') {
        const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
        existFile && fileList.pop();
      }
      this.uploadList = fileList;
      this.updateUploadListInfo(fileList);
    },
    fileOnRemove: function(file, fileList) {
      const attachId = file.id || (file.response ? file.response.data.id : 0);
      attachId && this.setValue(attachId, false);
    },
    fileOnProgress: function(event, file, fileList) {
      const current = this.uploadListInfo.find(item => item.name == event.name);
      current.status = event.percent + '%';
    },
    fileOnSuccess: function(response, file, fileList) {
      const attachId = file.id || response.data.id;
      this.setValue(attachId, true);
    },
    setValue: function(attachId, action) {
      if (action === true) {
        // 添加
        this.attach_ids.push(attachId);
      } else {
        this.attach_ids.splice(this.attach_ids.findIndex(item => item === attachId), 1);
      }
    },
    removeFile: function(name) {
      this.uploadList.splice(this.uploadList.findIndex(item => item.name == name), 1);
      this.updateUploadListInfo(this.uploadList);
    },
    updateUploadListInfo: function(fileList) {
      this.uploadListInfo = [];
      fileList.forEach(file => {
        let status = '待上传';
        switch (file.status) {
          case 'ready':
            status = '待上传';
            break;
          case 'success':
            status = '上传完成';
            break;
        }
        const item = {
          name: file.name,
          size: this.renderSize(file.size),
          status: status,
          action: ''
        };

        this.uploadListInfo.push(item);
      });
    }
  }
};
</script>

<style></style>
